class Solution {
public:
    int ret = 0;
    int find(TreeNode* root){
        if(!root){
            return 0;
        }
        
        int l = find(root->left);
        int r = find(root->right);
        
        if(root->left && root->left->val == root->val && root->right && root->right->val == root->val){
            ret = max(ret,l+r+2);
            return max(l+1,r+1);
        }
        
        if(root->left && root->left->val == root->val){
            l += 1;
            ret = max(ret,max(l,r));
            return l;
        }
        
        if(root->right && root->right->val == root->val){
            r += 1;
            ret = max(ret,max(l,r));
            return r;
        }
        
        return 0;
    }
    
    int longestUnivaluePath(TreeNode* root) {
        if(!root) return 0;
        find(root);
        return ret;
    }
};
